package com.leyou.search.EsTest;

import com.leyou.LySearchService;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.SpuBo;
import com.leyou.search.FeignClient.GoodsClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.lucene.search.IndexSearcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = LySearchService.class)
public class ElasticSearch {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private IndexService indexService;

    @Test
    public void createIndex() {
        template.createIndex(Goods.class);
        template.putMapping(Goods.class);
    }

    @Test
    public void testUploadData() {

        Integer page = 1;
        while (true) {
            PageResult<SpuBo> result = goodsClient.querySpuByPage(page, 50, true, null);

            if (result == null) {
                break;
            }
            List<Goods> goodsList = new ArrayList<>();
            result.getItems().forEach(spuBo -> {
                goodsList.add(indexService.buildGoods(spuBo));
            });
            goodsRepository.saveAll(goodsList);
            page++;
        }
    }
}
